package com.pond.pond.websocket;

import com.alibaba.fastjson2.JSONObject;
import com.pond.common.core.domain.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ws/send")
public class WebSocketMessageController {

    private final WebSocketHandler webSocketHandler;

    public WebSocketMessageController(WebSocketHandler webSocketHandler) {
        this.webSocketHandler = webSocketHandler;
    }

    @PostMapping
    public R<String> sendMessage(@RequestBody String messageStr) {
        JSONObject message = JSONObject.parseObject(messageStr);

        String type = message.getString("type");
        String to = message.getString("to");
        String pondId = message.getString("pondId");

        switch (type) {
            case "private":
                if (to != null) {
                    webSocketHandler.sendToUser(to, messageStr);
                    return R.ok("私聊消息发送成功");
                } else {
                    return R.fail("缺少目标用户ID");
                }
            case "group":
                if (pondId != null) {
                    webSocketHandler.sendToGroup(pondId, messageStr);
                    return R.ok("群聊消息发送成功");
                } else {
                    return R.fail("缺少钓场ID pondId");
                }
            case "admin":
                webSocketHandler.sendToAdmins(messageStr);
                return R.ok("管理员消息发送成功");
            default:
                return R.fail("未知消息类型");
        }
    }
}
